"use strict";

const {VueLoaderPlugin} = require('vue-loader');
const TerserPlugin = require('terser-webpack-plugin');

const RawSource = require('webpack-sources/lib/RawSource.js')

class AddExportDefault {
    apply(compiler) {
        compiler.hooks.emit.tap("sbt-vuefy-compilation", (compilation) => {
            const pathModule = require('path')
            let assets = compilation.assets;
            let keys = Object.keys(assets)
            keys.forEach(key=>{
                if(key.indexOf("json") === -1){
                    let  tokens = key.split(pathModule.sep);
                    let name =     tokens[tokens.length - 1]
                        .replace(/(\-\w)/g, (matches) => { return matches[1].toUpperCase(); })
                        .replace(/(^\w)/, (matches) => { return matches[0].toUpperCase(); })
                        .split('.')[0]
                    let asset = assets[key]
                    assets[key]  = new RawSource(asset.source() + "\n export default " +name +".default;")
                }
            })
        });
    }
}

module.exports = {
    mode: 'development',
    plugins: [
        new VueLoaderPlugin(),
        new AddExportDefault()
    ],
    cache: true,
    bail: true,
    stats: 'minimal',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                options: {
                    appendTsSuffixTo: [/\.vue$/],
                }
            },
            {
                test: /\.scss$/,
                exclude: /node_modules/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader'
                ],
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
        ]
    },
    externals: {
        // The below allows Typescript to `import Vue from 'vue'` without including Vue in the bundle.
        vue: 'Vue'
    },
    resolve: {
        extensions: ['.ts', '.js', '.vue']
    },
    performance: {
        hints: 'error',
        maxAssetSize: 1500000,
        maxEntrypointSize: 1500000,
        assetFilter: function (assetFilename) {
            return assetFilename.endsWith('.js');
        }
    },
    devtool: 'eval-cheap-source-map',
    optimization: {
        minimizer: [
            new TerserPlugin({
                parallel: true,
                terserOptions: {
                    format: {
                        comments: false
                    }
                }
            })
        ]
    }
};

